from pathlib import Path
import json
from typing import Optional
import sys

# 简化导入方式
try:
    # 先尝试直接导入
    from reqapi.api import BaseApi, ApiConfig
    from model.app_count_models import AddAppUpCountRequest, AddAppUpCountResponse
except ImportError:
    # 如果直接导入失败，尝试使用相对导入
    from ..api import BaseApi, ApiConfig
    from .model.app_count_models import AddAppUpCountRequest, AddAppUpCountResponse


class AppCountApi(BaseApi):
    """应用计数API"""
    
    def add_app_up_count(self, auth_token: str, raise_on_error: bool = False) -> Optional[AddAppUpCountResponse]:
        """上报应用计数，日志风格与统一API一致，异常和错误码时返回None"""
        endpoint = "/api/youpin/bff/addAppUpCount"
        url = f"{self.BASE_URL}{endpoint}"
        request = AddAppUpCountRequest(
            Sessionid=self.device_id or ""
        )
        request_data = {
            "Sessionid": request.Sessionid
        }
        headers = self.common_headers.copy()
        headers["apptype"] = "4"
        headers["authorization"] = auth_token
        print("\n=== 请求信息 ===")
        print(f"请求URL: {url}")
        print(f"请求方法: POST")
        print(f"请求头: {json.dumps(headers, indent=2, ensure_ascii=False)}")
        print(f"请求数据: {json.dumps(request_data, indent=2, ensure_ascii=False)}")
        try:
            response = self.interceptor.send_request(url, json=request_data, headers=headers, need_encrypt=False)
            print("\n=== 响应信息 ===")
            if isinstance(response, dict):
                resp_json = response
            elif hasattr(response, 'json'):
                resp_json = response.json()
            else:
                resp_json = response
            print(f"响应内容: {json.dumps(resp_json, indent=2, ensure_ascii=False)}")
            if resp_json.get('code', 0) != 0:
                print(f"API返回错误: {resp_json.get('msg', '未知错误')}")
                if raise_on_error:
                    raise Exception(f"业务处理失败: {resp_json.get('msg')}")
                return None
            return AddAppUpCountResponse(**resp_json)
        except Exception as e:
            print(f"请求发生错误: {str(e)}")
            if raise_on_error:
                raise
            return None


def main():
    """测试应用计数上报API"""
    try:
        device_id = "Z+Z/Uj4xyKoDAJp249r21qHx"
        auth_token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxMjQ1NWYyYmUxYmE0YzhiYjM5ZDlmYTFjZDc4N2NhNyIsIm5hbWVpZCI6IjEwMTAxMTE2IiwiSWQiOiIxMDEwMTExNiIsInVuaXF1ZV9uYW1lIjoi5oiR5pivMTgwIiwiTmFtZSI6IuaIkeaYrzE4MCIsInZlcnNpb24iOiJNcjAiLCJuYmYiOjE3NDMyMTQyNzUsImV4cCI6MTc0NzIxMDI3NSwiaXNzIjoieW91cGluODk4LmNvbSIsImRldmljZUlkIjoiWitaL1VqNHh5S29EQUpwMjQ5cjIxcUh4IiwiYXVkIjoidXNlciJ9.DuG5wsI03sCsNV4YixGuO2Ogb-wOJAf8uhP09qxZgdE"
        api = AppCountApi(
            device_token=device_id,
            device_id=device_id,
            auth_token="",
            uk="5FGaLrLar6b7EWUnNmqNpKGjU88E7TrsHnqsWlwo9ncsogqazR1hLGldi30biVJ1N"
        )
        response = api.add_app_up_count(auth_token)
        print("\n=== 应用计数上报结果 ===")
        if response is None:
            print("应用计数上报失败，可能是登录信息失效或接口返回错误。")
        else:
            print(f"状态码: {response.code}")
            print(f"消息: {response.msg}")
            print(f"时间戳: {response.timestamp}")
            print(f"是否成功: {response.data}")
        return response.data if response else False
    except Exception as e:
        print(f"应用计数上报失败: {e}")
        return False


if __name__ == "__main__":
    main()
